import ClassSelect from "@/components/ClassSelect";
import request from "@/services/interceptors";
import { enumValuesAtom } from "@/store/enum";
import { AddEditProps, ClassType, PaperType, TeacherType } from "@/types";
import { PlusOutlined } from "@ant-design/icons";
import {
  ModalForm,
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormItem,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import { Button, Form, message } from "antd";
import { useAtomValue } from "jotai";
import { useEffect, useState } from "react";
import TeacherSelect from "./TeacherSelect";
import PaperSelect from "./PaperSelect";

const AddExam = ({ editData, onSuccess, trigger }: AddEditProps) => {
  const [form] = Form.useForm<ClassType>();
  const { courseList } = useAtomValue(enumValuesAtom);
  const [initClass, setInitClass] = useState<ClassType[]>([]);
  const [initTeacher, setInitteacher] = useState<TeacherType[]>([]);
  const [initPaper, setInitPaper] = useState<PaperType[]>([]);
  const onOpenChange = async (visible: boolean) => {
    if (visible) {
      if (editData) {
        const { data }: any = await request.sgks.examDetailList({
          id: editData?.id,
        });
        // const res1: any = await request.sgks.teacherGetList({
        //   teacherId: data?.teacherId,
        // });
        setInitteacher(data?.teachers ?? []);
        const res2: any = await request.sgks.classGetList({
          classId: data?.classId,
        });
        setInitClass([{ ...res2.data }]);
        const res3: any = await request.sgks.paperDetailList({
          id: data?.paperId,
        });
        setInitPaper([{ ...res3.data }]);
        setTimeout(() => {
          form.setFieldsValue({
            ...data,

            classId: [data.classId],
            paperId: [data.paperId],
            teacherId: data?.teachers.map((i) => i.teacherId) ?? [],
          } as any);
        });
      }
    }
  };

  return (
    <ModalForm<ClassType>
      onOpenChange={onOpenChange}
      title={editData ? "编辑考试" : "新建考试"}
      trigger={
        trigger || (
          <Button type="primary" icon={<PlusOutlined />}>
            新增
          </Button>
        )
      }
      labelCol={{ span: 6 }}
      layout="horizontal"
      width={640}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => console.log("run"),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        if (editData) {
          await request.sgks.examUpdateCreate({
            ...values,
            teacherId: values.teacherId,
            classId: values.classId[0],
            paperId: values.paperId[0],
            id: editData.id,
            opt: 2,
          });
        } else {
          await request.sgks.examCreateCreate({
            ...values,
            teacherId: values.teacherId,
            classId: values.classId[0],
            paperId: values.paperId[0],
            opt: 1,
          });
        }
        message.success("提交成功");
        onSuccess?.();
        return true;
      }}
    >
      <ProFormText rules={[{ required: true }]} name="name" label="考试名称" />
      <ProFormItem
        rules={[{ required: true }]}
        required
        name="paperId"
        label="试卷"
      >
        <PaperSelect initData={initPaper} multiple={false} />
      </ProFormItem>
      <ProFormItem
        rules={[{ required: true }]}
        required
        name="classId"
        label="班级"
      >
        <ClassSelect initClass={initClass} multiple={false} />
      </ProFormItem>
      <ProFormSelect
        required
        name="courseId"
        label="所属课程"
        rules={[{ required: true }]}
        options={courseList}
      />
      <ProFormDigit
        label="考试时长(分钟)"
        name="duration"
        min={1}
        rules={[{ required: true }]}
        fieldProps={{ precision: 0 }}
      />
      <ProFormDateTimePicker
        label="考试开始时间"
        name="planStartTime"
        rules={[{ required: true }]}
        fieldProps={{
          disabledDate: (current) => {
            // 只能选择当前时间之后的时间
            return (
              current &&
              current.valueOf() <
                Date.now() -
                  (new Date().getHours() * 3600 +
                    new Date().getMinutes() * 60 +
                    new Date().getSeconds()) *
                    1000
            );
          },
        }}
      />
      <ProFormItem name="teacherId" label="教师" rules={[{ required: true }]}>
        <TeacherSelect initData={initTeacher} multiple={true} />
      </ProFormItem>
    </ModalForm>
  );
};

export default AddExam;
